<template>
  <div class="recharge-container">
    
    <!-- 页面标题栏 -->
    <div class="page-title-bar">
      <i class="back-icon" @click="handleBack">←</i>
      <span class="page-title">充值</span>
    </div>

    <!-- 账户信息 -->
    <div class="account-info">
      <div v-if="loading" class="loading-info">
        <i class="el-icon-loading"></i>
        <span>正在获取设备信息...</span>
      </div>
      <template v-else>
        <div class="info-item">
          <span class="label">用户名称</span>
          <span class="value">{{ userInfo && userInfo.userName ? userInfo.userName : '未知' }}</span>
        </div>
        <div class="info-item">
          <span class="label">缴费单位</span>
          <span class="value">{{ powerPointInfo && powerPointInfo.powerName ? powerPointInfo.powerName : '未知' }}</span>
        </div>
      </template>
    </div>

    <!-- 充值金额选择 -->
    <div class="recharge-amount">
      <div class="amount-options">
        <div 
          v-for="amount in amountOptions" 
          :key="amount"
          class="amount-option"
          :class="{ active: selectedAmount === amount && !isCustomAmount }"
          @click="selectAmount(amount)"
        >
          {{ amount }}元
        </div>
        <div 
          class="amount-option"
          :class="{ active: isCustomAmount }"
          @click="selectCustomAmount"
        >
          其他金额
        </div>
      </div>
      
      <!-- 自定义金额输入框 -->
      <div v-if="isCustomAmount" class="custom-amount">
        <input 
          type="number"
          v-model="customAmount"
          @input="handleCustomAmountInput"
          @blur="validateCustomAmount"
          class="amount-input"
          placeholder="请输入金额"
          min="1"
          max="100"
        />
        <div v-if="customAmountError" class="error-message">{{ customAmountError }}</div>
      </div>
    </div>

    <!-- 协议和充值按钮 -->
    <div class="agreement-section">
      <div class="agreement-checkbox">
        <input 
          type="checkbox" 
          id="agreement" 
          v-model="agreedToTerms"
          class="checkbox-input"
        />
        <label for="agreement" class="checkbox-label">
          我已阅读并同意
          <span class="agreement-link" @click="showAgreement">《共享用电智能交费服务协议》</span>
        </label>
      </div>
      
      <button 
        class="recharge-btn"
        :disabled="!agreedToTerms || !canRecharge || loading || !deviceInfo || deviceInfo.deviceStatus != 2"
        @click="handleRecharge"
      >
        {{ loading ? '获取设备信息中...' : '立即充值' }}
      </button>
    </div>

    <!-- 附加信息 -->
    <div class="additional-info">
      <div class="info-line">*当前执行电价: {{ electricityPrice }}元/度</div>
      <div class="info-line">*最大支持功率: {{ deviceInfo.powerCapacity }}kW</div>
    </div>

    <!-- 协议对话框 -->
    <el-dialog
      title="共享用电智能交费服务协议"
      :visible.sync="agreementDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      class="agreement-dialog"
    >
      <div class="agreement-content">
        <h4>第一条 服务内容</h4>
        <p>本协议是用户与共享用电智能交费服务平台之间关于用电充值服务的协议。平台为用户提供便捷的在线充值服务，支持多种支付方式。</p>
        
        <h4>第二条 用户权利与义务</h4>
        <p>1. 用户有权享受平台提供的充值服务；</p>
        <p>2. 用户应确保提供的电表信息准确无误；</p>
        <p>3. 用户应遵守相关法律法规和平台规则。</p>
        
        <h4>第三条 平台权利与义务</h4>
        <p>1. 平台应提供安全、稳定的充值服务；</p>
        <p>2. 平台应保护用户个人信息和支付安全；</p>
        <p>3. 平台有权对异常交易进行风险控制。</p>
        
        <h4>第四条 充值规则</h4>
        <p>1. 充值金额最低20元，最高10000元；</p>
        <p>2. 充值成功后，电费将实时到账；</p>
        <p>3. 如遇充值失败，平台将及时处理退款。</p>
        
        <h4>第五条 免责声明</h4>
        <p>1. 因不可抗力导致的充值延迟，平台不承担责任；</p>
        <p>2. 用户因操作失误造成的损失，平台不承担责任；</p>
        <p>3. 平台将尽最大努力保障服务稳定运行。</p>
        
        <h4>第六条 协议修改</h4>
        <p>平台有权根据业务发展需要修改本协议，修改后的协议将在平台公示，继续使用服务视为同意修改后的协议。</p>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="agreementDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createPayOrder } from '@/api/wechat'
import { listDevice } from '@/api/device/device'
import { Message } from 'element-ui'
import { getUserProfile } from '@/api/system/user'
import { getElectricityPrice } from '@/api/config/config'
import { listRecharge } from '@/api/business/recharge'

export default {
  name: 'WechatRecharge',
  data() {
    return {
      meterNo: '', // 从URL获取的表号
      deviceInfo: null, // 设备信息
      powerPointInfo: null, // 用电点信息
      userInfo: null, // 用户信息
      loading: false, // 加载状态
      agreementDialogVisible: false, // 协议对话框显示状态
      selectedAmount: 20, // 默认选择20元
      customAmount: '20', // 自定义金额
      isCustomAmount: false, // 是否选择其他金额
      customAmountError: '', // 自定义金额错误信息
      agreedToTerms: true, // 是否同意协议
      amountOptions: [5, 10, 20, 50, 100], // 预设金额选项
      electricityPrice: 0.0 // 电价
    }
  },
  computed: {
    canRecharge() {
      if (!this.customAmount || this.customAmount === '') {
        return false
      }
      const amount = parseInt(this.customAmount, 10)
      // 必须是整数，且在1-100之间，且没有错误信息
      return !isNaN(amount) && Number.isInteger(amount) && amount >= 1 && amount <= 100 && !this.customAmountError
    }
  },
  mounted() {
    this.getDeviceInfo()
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      const result = await getUserProfile()
      this.userInfo = result.data
      if (this.userInfo.balance!==null && this.userInfo.balance > 0) {
        // 获取最新充值记录，status为1的
        const query = {
          userId: this.userInfo.userId,
          status: 1
        }
        const result = await listRecharge(query)
        window.orderId = result.rows[0].orderId
        window.amount = result.rows[0].amount
        this.$router.push('/wechat/useElectron')
      }
    },

    // 显示协议对话框
    showAgreement() {
      this.agreementDialogVisible = true
    },

    // 根据meterNo获取设备信息
    async getDeviceInfo() {
      this.loading = true
      try {
        const query = {
          meterNo: window.meterNo
        }
        
        const result = await listDevice(query)
        
        if (result.code === 200 && result.rows && result.rows.length > 0) {
          this.deviceInfo = result.rows[0]
          window.meterId = this.deviceInfo.id
          this.powerPointInfo = this.deviceInfo.powerPointInfo
          console.log('设备信息:', this.deviceInfo)
          if (this.deviceInfo.deviceStatus == 1) {
            Message.warning('设备未上线，无法进行充值')
            return
          } else if (this.deviceInfo.deviceStatus == 3) {
            Message.warning('设备使用中，无法进行充值')
            return
          }
          const resp = await getElectricityPrice(this.deviceInfo.prcCode)
          this.electricityPrice = resp.data
          this.getUserInfo()
        } else {
          Message.warning(`未找到表号为 ${this.meterNo} 的设备信息`)
        }
      } catch (error) {
        console.error('查询设备信息失败:', error)
        Message.error('查询设备信息失败')
      } finally {
        this.loading = false
      }
    },

    // 选择充值金额
    selectAmount(amount) {
      this.selectedAmount = amount
      this.customAmount = amount.toString()
      this.isCustomAmount = false
      this.customAmountError = ''
    },

    // 选择其他金额
    selectCustomAmount() {
      this.isCustomAmount = true
      this.selectedAmount = null
      this.customAmount = ''
      this.customAmountError = ''
    },

    // 处理自定义金额输入
    handleCustomAmountInput(event) {
      let value = event.target.value
      // 只允许输入数字
      value = value.replace(/[^\d]/g, '')
      this.customAmount = value
      this.customAmountError = ''
      
      // 实时验证
      if (value && value !== '') {
        const amount = parseInt(value, 10)
        if (isNaN(amount) || amount < 1) {
          this.customAmountError = '金额必须大于0'
        } else if (amount > 100) {
          this.customAmountError = '金额不能超过100元'
        }
        // 由于已经过滤了非数字字符，所以输入的肯定是整数
      }
    },

    // 验证自定义金额
    validateCustomAmount() {
      if (!this.customAmount || this.customAmount === '') {
        this.customAmountError = '请输入金额'
        return false
      }
      
      const amount = parseInt(this.customAmount, 10)
      if (isNaN(amount)) {
        this.customAmountError = '请输入有效的金额'
        return false
      }
      
      if (amount < 1) {
        this.customAmountError = '金额必须大于0'
        return false
      }
      
      if (amount > 100) {
        this.customAmountError = '金额不能超过100元'
        return false
      }
      
      // 验证是否为整数（由于输入时已经过滤了非数字字符，这个检查主要是为了确保）
      if (amount.toString() !== this.customAmount) {
        this.customAmountError = '金额必须为整数'
        return false
      }
      
      this.customAmountError = ''
      return true
    },

    // 处理返回
    handleBack() {
      this.$router.push('/wechat/index')
    },

    // 处理关闭
    handleClose() {
      this.$router.push('/wechat/index')
    },

    // 处理充值
    async handleRecharge() {
      if (!this.agreedToTerms) {
        Message.warning('请先同意服务协议')
        return
      }

      // 如果是自定义金额，先验证
      if (this.isCustomAmount && !this.validateCustomAmount()) {
        return
      }

      if (!this.canRecharge) {
        Message.warning('请输入有效的充值金额（1-100的整数）')
        return
      }

      if (!window.meterNo) {
        Message.error('表号信息缺失，无法进行充值')
        return
      }
      
      try {
        const amount = parseInt(this.customAmount)
        window.amount = amount
        const payRequest = {
          meterNo: window.meterNo,
          totalAmount: amount,
        }

        Message.info('正在创建支付订单...')
        
        const result = await createPayOrder(payRequest)
        
        if (result.code === 200) {
          Message.success('支付订单创建成功')
          // 调用微信支付
          const payParams = result.data
          console.log('支付参数:', payParams)
          window.orderId = payParams.outTradeNo
          // 检查是否在微信环境中
          if (typeof wx !== 'undefined') {
            // 使用微信JSSDK的chooseWXPay方法
            // 注意：参数名必须与后端返回的字段名完全一致
            wx.chooseWXPay({
              appId: payParams.appId,
              timestamp: payParams.timeStamp, // 注意这里是timeStamp，不是timestamp
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: (res) => {
                console.log('支付成功:', res)
                this.$message.success('支付成功！')
                this.$router.push('/wechat/useElectron')
              },
              fail: (res) => {
                console.log('支付失败:', res)
                if (res.errMsg && res.errMsg.includes('cancel')) {
                  this.$message.info('支付已取消')
                } else {
                  this.$message.error('支付失败，请重试')
                }
              }
            })
          } else {
            // 非微信环境，显示支付参数供调试
            this.$message.warning('当前不在微信环境中，无法调起支付')
            console.log('支付参数（非微信环境）:', payParams)
          }

        } else {
          Message.error(result.msg || '创建支付订单失败')
        }
      } catch (error) {
        console.error('充值失败:', error)
        Message.error('充值失败：' + error)
      }
    }
  }
}
</script>

<style scoped>
.recharge-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 状态栏样式 */
.status-bar {
  height: 44px;
  background: #000;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  font-size: 14px;
}

.time {
  font-weight: 500;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.signal, .wifi {
  font-size: 16px;
}

.battery {
  width: 24px;
  height: 12px;
  border: 1px solid white;
  border-radius: 2px;
  position: relative;
}

.battery-level {
  height: 100%;
  background: #4CAF50;
  border-radius: 1px;
}

/* 头部样式 */
.header {
  background: #4a90e2;
  color: white;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-center {
  text-align: center;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  margin: 4px 0 0 0;
  font-size: 12px;
  opacity: 0.8;
}

.close-icon, .more-icon {
  font-size: 20px;
  cursor: pointer;
  width: 24px;
  text-align: center;
}

/* 页面标题栏 */
.page-title-bar {
  background: #1976D2;
  color: white;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  position: relative;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
}

/* 账户信息 */
.account-info {
  background: white;
  margin: 16px;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-info {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.loading-info i {
  margin-right: 8px;
  font-size: 16px;
  color: #4a90e2;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

/* 充值金额选择 */
.recharge-amount {
  background: white;
  margin: 16px;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.amount-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
}

.amount-option {
  flex: 1;
  min-width: calc(50% - 6px);
  padding: 16px;
  text-align: center;
  border: 2px solid #4a90e2;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.amount-option.active {
  background: #4a90e2;
  color: white;
}

.amount-option:not(.active) {
  background: white;
  color: #4a90e2;
}

.custom-amount {
  margin-top: 16px;
}

.amount-input {
  width: 100%;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  text-align: center;
  box-sizing: border-box;
}

.amount-input:focus {
  outline: none;
  border-color: #4a90e2;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 8px;
  text-align: center;
}

/* 协议和充值按钮 */
.agreement-section {
  background: white;
  margin: 16px;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.agreement-checkbox {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 8px;
}

.checkbox-input {
  margin: 0;
  margin-top: 2px;
}

.checkbox-label {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.agreement-link {
  color: #4a90e2;
  text-decoration: underline;
}

.recharge-btn {
  width: 100%;
  padding: 16px;
  background: #4a90e2;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s;
}

.recharge-btn:hover:not(:disabled) {
  background: #357abd;
}

.recharge-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 附加信息 */
.additional-info {
  margin: 16px;
  padding: 0 20px;
}

.info-line {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

/* 底部导航 */
.bottom-nav {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 16px;
}

.nav-arrow {
  font-size: 20px;
  color: #ccc;
  cursor: pointer;
}

.nav-indicator {
  width: 40px;
  height: 4px;
  background: #ddd;
  border-radius: 2px;
}

/* 协议对话框样式 */
.agreement-dialog .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

.agreement-content {
  line-height: 1.6;
  color: #333;
}

.agreement-content h4 {
  color: #1976D2;
  margin: 20px 0 10px 0;
  font-size: 16px;
  font-weight: 600;
}

.agreement-content h4:first-child {
  margin-top: 0;
}

.agreement-content p {
  margin: 8px 0;
  text-indent: 0;
}

.dialog-footer {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .amount-option {
    min-width: calc(50% - 6px);
  }
}

@media (max-width: 375px) {
  .header, .page-title-bar {
    padding: 12px 16px;
  }
  
  .account-info, .recharge-amount, .agreement-section {
    margin: 12px;
    padding: 16px;
  }
  
  .amount-options {
    gap: 8px;
  }
  
  .amount-option {
    min-width: calc(50% - 4px);
    padding: 12px;
    font-size: 14px;
  }
}
</style>
